package com.yy.finvideoplayer.videoview

import android.content.Context
import android.database.ContentObserver
import android.graphics.Bitmap
import android.hardware.Sensor
import android.hardware.SensorEvent
import android.hardware.SensorEventListener
import android.hardware.SensorManager
import android.os.Handler
import android.os.Looper
import android.provider.Settings
import android.util.AttributeSet
import android.util.Log
import android.view.ViewGroup
import android.widget.FrameLayout
import com.yy.finvideoplayer.IVideoPlayer
import com.yy.finvideoplayer.MediaDecoderClass
import com.yy.finvideoplayer.PlayListener
import com.yy.finvideoplayer.Util
import com.yy.finvideoplayer.danmu.DMTextureView
import com.yy.finvideoplayer.ext.orZero
import com.yy.finvideoplayer.media.AndroidMedia
import com.yy.finvideoplayer.media.ExoMedia
import com.yy.finvideoplayer.media.IjkExoMedia
import com.yy.finvideoplayer.media.IjkMedia
import com.yy.finvideoplayer.model.PlayerOptions
import java.io.InputStream


/**
 * @Description: VideoPlayer
 * @Author: yiw89
 * @CreateDate: 2025/9/8 20:23
 * @Version: 1.0
 */
class VideoPlayer @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0,
    var playerOption: PlayerOptions
): FrameLayout(context,attrs,defStyleAttr), VideoControlView.IControlViewAction ,PlayListener,
    SensorEventListener {

    private val mediaVideoView: MediaVideoView = MediaVideoView(context)
    private val controlView: VideoControlView = VideoControlView(context, playerOptions = playerOption)
    private val dmView = DMTextureView(context)
    private var decodeMedia: MediaDecoderClass = null
    private

    companion object{
        private const val TAG = "VideoPlayer"
    }

    init {
        mediaVideoView.addPlayListener(this)
        addView(mediaVideoView,LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT))
        //添加弹幕
        //dmView.setIsSameLayer(isSameLayer)
        dmView.visibility = VISIBLE
        dmView.setOptions(playerOption)
        addView(dmView, LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT))
        addPlayListener(dmView)
        //添加控制ControllerView
        addView(controlView, LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT))
        addPlayListener(controlView)
        controlView.bindWith(this)

        //初始化属性
        initOptionsToVideoPlay()
    }


    private fun initOptionsToVideoPlay(){
        this.decodeMedia = when(playerOption.decoderType){
            PlayerOptions.DecoderType.MEDIA_PLAYER -> AndroidMedia::class.java
            //PlayerOptions.DecoderType.EXO_PLAYER -> IjkExoMedia::class.java
            PlayerOptions.DecoderType.EXO_PLAYER -> ExoMedia::class.java
            PlayerOptions.DecoderType.IJK_PLAYER -> IjkMedia::class.java
        }

        //将属性设置到video view中
        //videoView.coverImageView.setImageResource()
        //进入全屏的模式 0横屏 1竖屏 2传感器自动横竖屏 3根据视频比例自动确定横竖屏      -1什么都不做
        mediaVideoView.enterFullMode = when(playerOption.direction){
            null -> 3
            90,-90 -> 0
            else -> 1
        }
        //设置object-fit
        mediaVideoView.setObjectFit(playerOption.objectFit)

        //是否静音
        mediaVideoView.setMute(playerOption.muted)
        if(playerOption.initialTime>0){
            mediaVideoView.startPosition = playerOption.initialTime.toInt()
        }
        mediaVideoView.autoPlay = playerOption.autoplay
        mediaVideoView.isLooping = playerOption.loop
        controlView.updateUIWithOptions()
    }

    fun applyOptionUpdates(updates: Map<String, Any?>){
        var hasChangeUI = false
        updates.forEach{ (key, value) ->
            when(key){
                "src"-> start()
                /*"duration","danmuList","autoplay","direction","enableDanmu","danmuBtn"
                    ,"enableProgressGesture","poster","enablePlayGesture","vslideGesture"
                    ,"vslideGestureInFullscreen",
                ->{
                    //不需要处理
                }*/
                "controls","showProgress","showFullscreenBtn",
                    "showPlayBtn","showCenterPlayBtn","showMuteBtn","showBottomProgress",
                    "title","playBtnPosition"
                    ,"showBottomProgress","showScreenLockButton","showSnapshotButton"
                -> {
                    if(!hasChangeUI){
                        controlView.updateUIWithOptions()
                        hasChangeUI = true
                    }
                }
                "initialTime"->{
                    mediaVideoView.startPosition = playerOption.initialTime.toInt()
                }
                "objectFit"->{
                    mediaVideoView.setObjectFit(playerOption.objectFit)
                }
                "loop"->{
                    mediaVideoView.isLooping = value as Boolean
                }
                "muted"->{
                    mediaVideoView.setMute(value as Boolean)
                }
                "autoplay"->{
                    mediaVideoView.autoPlay = playerOption.autoplay
                }
            }
        }
    }

    fun start() {
        this.mediaVideoView.release()
        decodeMedia?.let { this.mediaVideoView.setDecodeMedia(it) }
        this.mediaVideoView.setUp(playerOption.src)
        this.mediaVideoView.prePlay()
    }

    //region Operation事件
    fun playOperation(){
        if(!mediaVideoView.isPlaying()){
            playAction()
        }

    }
    fun pauseOperation(){
        if(mediaVideoView.isPlaying())
            playAction()
    }

    fun stopOperation(){
        if(mediaVideoView.isPlaying()){
            playAction()
            mediaVideoView.isPlayerStop = true
        }

    }

    /**
     * 开始播放、暂停播放
     */
    private fun playAction(){
        mediaVideoView.handlePlayAction()

    }
    fun seekAction(position: Int){
        controlView.changeSeekBarProgressFromOperate(position*1000)
    }
    fun playBackRateAction(speed: Float){
        mediaVideoView.setSpeed(2.0f)
    }

    fun requestFullScreenAction(){
        enterWindowFullscreen()
    }
    fun exitFullScreenAction(){
        quitWindowFullscreen()
    }

    fun showControl(){
        this.mediaVideoView.videoContainer.performClick()
    }

    //endregion

    //region MediaVideoView与controlView的交互
    override fun handlePlayAction(){
        mediaVideoView.handlePlayAction()
    }

    override fun setMute(boolean: Boolean) {
        mediaVideoView.setMute(boolean)
    }

    private var originalLayoutParams: ViewGroup.LayoutParams? = null
    private var videoPlayerParent: ViewGroup? = null
    override fun quitWindowFullscreen() {

        if(mediaVideoView.currentMode == IVideoPlayer.MODE_WINDOW_FULLSCREEN){
            //todo
            Log.e(TAG, "quitWindowFullscreen 退出全屏")
            mediaVideoView.quitWindowFullscreen()
            val container = parent as? ViewGroup
            container?.removeView(this)

            videoPlayerParent?.addView(this, originalLayoutParams?: ViewGroup.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT))
        }
    }

    override fun enterWindowFullscreen() {
        if(mediaVideoView.currentMode == IVideoPlayer.MODE_WINDOW_NORMAL){
            //todo
            Log.e(TAG, "enterWindowFullscreen 进入全屏")
            //获取父容器
            videoPlayerParent = parent as ViewGroup
            //获取在父容器的布局参数
            originalLayoutParams = layoutParams

            mediaVideoView.enterWindowFullscreen()

            val container = parent as? ViewGroup
            container?.removeView(this)
            val decorView = Util.scanForActivity(context).window.decorView as ViewGroup
            decorView.addView(this, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)
        }

    }

    override fun getPosition(): Int {
        return mediaVideoView.getPosition()
    }

    override fun getDuration(): Int {
        return mediaVideoView.getDuration()
    }

    override fun checkReady(): Boolean {
        return mediaVideoView.checkReady()
    }

    override fun seekTo(duration: Int) {
        mediaVideoView.seekTo(duration)
    }

    override fun showDanmu() {
        setDanmuEnable(true)
    }

    override fun hideDanmu() {
        setDanmuEnable(false)
    }

    override fun printDanmu(position: Int) {
        dmView.handlePrintDanmu(position)
    }

    override fun getCurrentFrame(): Bitmap? {
        return mediaVideoView.getCurrentFrame()
    }

    fun isPlaying():Boolean{
        return mediaVideoView.isPlaying()
    }
    fun addPlayListener(playListener: PlayListener){
        mediaVideoView.addPlayListener(playListener)
    }
    fun isWindowFloatMode():Boolean{
        return mediaVideoView.isWindowFloatMode()
    }

    fun removePlayListener(playListener: PlayListener){
        mediaVideoView.removePlayListener(playListener)
    }
    // endregion

    fun setDanmuEnable(enable: Boolean) {
        dmView.emitter.isActive = enable
        dmView.controller?.clean()
        dmView.visibility = if (enable) {
            //if (isSameLayer) INVISIBLE else VISIBLE
            VISIBLE
        } else {
            GONE
        }
        if (enable /*&& !isSameLayer*/) {
            dmView.controller?.start()
        }
    }

    fun sendDanmu(text: String, color: String) {
        val danmuItem =
            PlayerOptions.DanmakuItem( text,(mediaVideoView.getPosition().orZero() / 1000).toLong(), color)
        dmView.myDanmuList.add(danmuItem)
//        emitter.insertDanmuItem(danmuItem)
//        emitter.send( + 500, text, color)
    }

    //region 监听横竖屏
    private var isAutoRotationEnabled = false
    private lateinit var sensorManager: SensorManager
    private var accelerometer: Sensor? = null
    //private var isLandscape = false
    private var lastOrientationChangeTime = 0L
    private val orientationChangeDelay = 1500L // 防抖延迟

    private val rotationSettingsObserver = object : ContentObserver(Handler(Looper.getMainLooper())) {
        override fun onChange(selfChange: Boolean) {
            Log.e(TAG, "ContentObserver selfChange = $selfChange")
            checkAutoRotationStatus()
        }
    }
    private fun checkAutoRotationStatus() {
        val newStatus = Util.isAutoRotationEnabled(context)

        if (newStatus != isAutoRotationEnabled) {
            isAutoRotationEnabled = newStatus
            if (isAutoRotationEnabled && playerOption.enableAutoRotation) {
                // 开启自动旋转：开始监听传感器
                startOrientationListener()
            } else {
                // 关闭自动旋转：停止监听传感器
                stopOrientationListener()
                // 确保保持在当前方向（不自动切换）
            }
        }
    }
    private fun startOrientationListener() {
        accelerometer?.let {
            sensorManager.registerListener(this, it, SensorManager.SENSOR_DELAY_NORMAL)
        }
    }

    private fun stopOrientationListener() {
        sensorManager.unregisterListener(this)
    }

    override fun onSensorChanged(event: SensorEvent) {
        if (!isAutoRotationEnabled) return // 确保只有在自动旋转开启时才处理

        val x = event.values[0]
        val y = event.values[1]

        // 计算设备方向（简化逻辑）
        val isCurrentlyLandscape = Math.abs(x) > Math.abs(y)

        // 防抖处理
        val currentTime = System.currentTimeMillis()
        if (currentTime - lastOrientationChangeTime < orientationChangeDelay) {
            return
        }

        if (isCurrentlyLandscape && mediaVideoView.currentMode == IVideoPlayer.MODE_WINDOW_NORMAL) {
            // 设备横屏，但当前是竖屏 -> 切换到横屏
            enterWindowFullscreen()
            lastOrientationChangeTime = currentTime
        } else if (!isCurrentlyLandscape && mediaVideoView.currentMode == IVideoPlayer.MODE_WINDOW_FULLSCREEN) {
            // 设备竖屏，但当前是横屏 -> 切换到竖屏
            exitFullScreenAction()
            lastOrientationChangeTime = currentTime
        }
    }

    override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) {

    }

    //============================
    /*private var orientationEventListener: OrientationEventListener? = null
    private var currentOrientation = Configuration.ORIENTATION_UNDEFINED
    //private var lastOrientationChangeTime: Long = 0
    private val ORIENTATION_CHANGE_DELAY: Long = 300 // 防抖延迟300ms
    private fun startOrientationListening() {
        orientationEventListener = object : OrientationEventListener(context, SensorManager.SENSOR_DELAY_NORMAL) {
            override fun onOrientationChanged(orientation: Int) {
                if(!Util.isAutoRotationEnabled(context)) return
                handleOrientationChange(orientation);
            }
        }

        if ((orientationEventListener as OrientationEventListener).canDetectOrientation()) {
            (orientationEventListener as OrientationEventListener).enable()
        }
    }

    private fun stopOrientationListening() {
        if (orientationEventListener != null) {
            orientationEventListener!!.disable()
            orientationEventListener = null
        }
    }

    private fun handleOrientationChange(orientation: Int) {
        if (orientation == ORIENTATION_UNKNOWN) {
            return
        }

        val newOrientation: Int = calculateScreenOrientation(orientation)

        // 防抖处理：避免频繁切换
        val currentTime = System.currentTimeMillis()
        if (newOrientation != currentOrientation &&
            currentTime - lastOrientationChangeTime > ORIENTATION_CHANGE_DELAY
        ) {
            currentOrientation = newOrientation
            lastOrientationChangeTime = currentTime

            post { notifyOrientationChange(currentOrientation, orientation) }
        }
    }

    private fun calculateScreenOrientation(orientation: Int): Int {
        // 使用容差范围来避免边界抖动
        if (isInRange(orientation, 340, 20) || isInRange(orientation, 160, 200)) {
            return Configuration.ORIENTATION_PORTRAIT
        } else if (isInRange(orientation, 70, 110) || isInRange(orientation, 250, 290)) {
            return Configuration.ORIENTATION_LANDSCAPE
        }
        return Configuration.ORIENTATION_UNDEFINED
    }

    private fun isInRange(value: Int, start: Int, end: Int): Boolean {
        // 处理360度循环
        if (start > end) {
            return value >= start || value <= end
        }
        return value in start..end
    }
    private fun notifyOrientationChange(orientation: Int, rawAngle: Int) {
        when (orientation) {
            Configuration.ORIENTATION_PORTRAIT -> {
                Log.d("Orientation", "竖屏 - 原始角度: $rawAngle°")
                onPortraitOrientation()
            }

            Configuration.ORIENTATION_LANDSCAPE -> {
                Log.d("Orientation", "横屏 - 原始角度: $rawAngle°")
                onLandscapeOrientation()
            }
        }
        //请求重新布局
        requestLayout()
    }

    private fun onPortraitOrientation() {
        // 竖屏处理逻辑
        // 例如：调整布局、改变UI等
        quitWindowFullscreen()
    }*/

    /*private fun onLandscapeOrientation() {
        // 横屏处理逻辑
        // 例如：调整布局、改变UI等
        enterWindowFullscreen()
    }*/

    override fun onAttachedToWindow() {
        super.onAttachedToWindow()

        sensorManager = context.getSystemService(Context.SENSOR_SERVICE) as SensorManager
        accelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER)
        registerContentObserver()

        if(controlView!=null){

        }


        /*if(playerOption.enableAutoRotation && Util.isAutoRotationEnabled(context)){
            startOrientationListening()
        }*/

    }

    override fun onDetachedFromWindow() {
        super.onDetachedFromWindow()
        unregisterContentObserver()

        //stopOrientationListening()
    }

    private fun registerContentObserver() {
        context.contentResolver.registerContentObserver(
            Settings.System.getUriFor(Settings.System.ACCELEROMETER_ROTATION),
            false,
            rotationSettingsObserver
        )
    }

    private fun unregisterContentObserver() {
        context.contentResolver.unregisterContentObserver(rotationSettingsObserver)
    }

    //endregion



    fun release(){
        mediaVideoView.release()
        mediaVideoView.removePlayListener(this)
        mediaVideoView.removeView(controlView)
        mediaVideoView.removeView(dmView)

        removeView(mediaVideoView)
        removeView(controlView)
        removeView(dmView)

        (parent as ViewGroup)?.removeView(this)

    }

    //region PlayList
    override fun onStatusAndMode(status: Int, mode: Int) {
        /*when(mode){
            IVideoPlayer.MODE_WINDOW_NORMAL ->{
                Log.e(TAG, "videoPlayer 退出全屏")
            }
            IVideoPlayer.MODE_WINDOW_FULLSCREEN ->{
                Log.e(TAG, "videoPlayer 进入全屏")
            }
        }*/
        /*if(IVideoPlayer.STATE_AUTO_COMPLETE == status){
            quitWindowFullscreen() //播放完成退出全屏
        }*/
    }

    override fun onEvent(status: Int, vararg extra: Int?) {
        when (status) {
            IVideoPlayer.EVENT_PREPARE_START -> {
                Log.e(TAG, "videoPlayer 准备开始")
            }
            IVideoPlayer.EVENT_PREPARE_END -> {
                Log.e(TAG, "videoPlayer 准备结束")
            }
            IVideoPlayer.EVENT_PLAY -> {
                Log.e(TAG, "videoPlayer 开始播放")
            }
            IVideoPlayer.EVENT_PAUSE -> {
                Log.e(TAG, "videoPlayer 暂停播放")
            }
            IVideoPlayer.EVENT_ERROR -> {
                Log.e(TAG, "videoPlayer 播放错误")
            }
            IVideoPlayer.EVENT_COMPLETION -> {
                Log.e(TAG, "videoPlayer 播放完成")
                quitWindowFullscreen() //播放完成退出全屏
            }
            IVideoPlayer.EVENT_RELEASE -> {
                Log.e(TAG, "videoPlayer 播放器释放")
            }
            IVideoPlayer.EVENT_BUFFERING_START -> {
                Log.e(TAG, "videoPlayer 播放缓冲开始")
            }
            IVideoPlayer.EVENT_SEEK_TO -> {
                Log.e(TAG, "videoPlayer 播放器seekTo")
            }
             IVideoPlayer.EVENT_BUFFERING_END -> {
                 Log.e(TAG, "videoPlayer 播放缓冲结束")
            }
            IVideoPlayer.EVENT_SEEK_COMPLETION -> {
                Log.e(TAG, "videoPlayer 播放seekCompletion")

            }
        }
    }
    //endregion

}